﻿using System;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using QAToolsAddin.Components;

namespace QAToolsAddin.GenericDialogs.Fields {

    public class FieldText : Field, IField {
        readonly ExcelRefEdit _control;
        private readonly string _pattern;
        private readonly string _errormsg;
        public int MaxValues { get; set; }
        public int NumberOfValues { get; set; }

        public override event EventHandler KeyReturn {
            add { _control.KeyReturn += delegate { value.Invoke(this, null); }; }
            remove { _control.KeyReturn += delegate { value.Invoke(this, null); }; }
        }

        public FieldText(string name, string info, string value, bool retore = false)
            : this(name, info, value, null, null, retore) { }

        public FieldText(string name, string info, string value, string pattern, string errormsg, bool retore = false)
            : base(name, info, retore) {
            _pattern = pattern;
            _errormsg = errormsg;
            _control = new ExcelRefEdit {
                AllowTextInput = true,
                DisplayMode = ExcelRefEdit.XlMode.ValueText,
                Delimiter = ";",
                Text = value
            };
            MaxValues = -1;
            NumberOfValues = -1;
        }

        public override Control Control {
            get { return _control; }
        }

        public string Value {
            get { return _control.Text; }
            set { _control.Text = value; }
        }

        object IField.Value {
            get { return Value; }
            set { Value = (string)value; }
        }

        public override bool Validate(out string errorMessage) {
            errorMessage = null;
            if (_pattern != null && Regex.IsMatch(_control.Text, _pattern) == false)
                errorMessage = _errormsg;
            else if (MaxValues != -1 && CountValues(_control.Text) > MaxValues)
                errorMessage = "Maximum number of values : " + MaxValues;
            else if (NumberOfValues != -1 && CountValues(_control.Text) != NumberOfValues)
                errorMessage = "Nuumber of values required : " + NumberOfValues;
            else return true;
            _control.SelectAll();
            return false;
        }

        private int CountValues(string text) {
            int count = 0;
            foreach (char c in text)
                if (c == ';') count++;
            if (count > 0)
                return count + 1;
            return 0;
        }

    }

}